import axios from 'axios'
import store from '@/store'
import { get } from 'lodash'
import { getToken, setToken } from '@/utils/auth'
import { removeToken } from '@/utils/auth'
import router from '@/router'
import { dataNotFound, errorCreate,errorLog  } from '@/utils/tools'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
   // for debug
    return Promise.reject(new Error(error || 'Error'))
  }
)
export function getErrorMessage (msg) {
  if (typeof msg === 'string') {
    return msg
  }
  if (typeof msg === 'object') {
    if (msg.code === 'token_not_valid') {
      removeToken()
      // router.push({ path: '/login/' })
      window.location.reload()
      return '登录超时，请重新登录！'
    }
    if (msg.code === 'user_not_found') {
      removeToken()
      // router.push({ path: '/login/' })
      window.location.reload()
      return '用户无效，请重新登录！'
    }
    return Object.values(msg)
  }
  if (Object.prototype.toString.call(msg).slice(8, -1) === 'Array') {
    return msg
  }
  return msg
}

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    if (response.headers['content-disposition']) {
      res = response
    }
    // if the custom code is not 20000, it is judged as an error.
    const { code } = res
    switch (code) {
      case 2000:
        return res
      case 401:
        errorCreate(`${getErrorMessage(res.msg)}`)
        break
      case 404:
        dataNotFound(`${res.msg}`)
        break
      case 4000:
        // 删除cookie
        errorCreate(`${getErrorMessage(res.msg)}`)
        break
      case 2002:
        // 删除cookie
      errorCreate(`${getErrorMessage('与数据服务器断开，请联系管理员！')}`)
      break
      case 400:
        errorCreate(`${res.msg}`)
        break
      default:
        // 不是正确的 code
        errorCreate(`${res.msg}: ${response.config.url}`)
        break
    }
  },
  error => {
    const status = get(error, 'response.status')
    switch (status) {
      case 400:
          error.message = '请求错误'
          break
        case 401:
          refreshToken().then(res => {
            setToken('token', res.access)
          }).catch(e => {
            router.push({ name: 'login' })
            router.go(0)
            error.message = '未认证，请登录'
          })
          break
        case 403:
          error.message = '拒绝访问'
          break
        case 404:
          error.message = `请求地址出错: ${error.response.config.url}`
          break
        case 408:
          error.message = '请求超时'
          break
        case 500:
          error.message = '服务器内部错误'
          break
        case 501:
          error.message = '服务未实现'
          break
        case 502:
          error.message = '网关错误'
          break
        case 503:
          error.message = '服务不可用'
          break
        case 504:
          error.message = '网关超时'
          break
        case 505:
          error.message = 'HTTP版本不受支持'
          break
        default:
          break
    }
    errorLog(error)
    return Promise.reject(error)
  }
)
export default service
